<template>
	<view>
		<!-- 顶部导航 -->
		<mnav-bar backState="2000" fontColor="#FFF" :titleCenter="false" type="transparent">
			<view slot="left">
				<image class="hicon" src="../static/back.png" mode="aspectFit" @tap="goBack" />
			</view>
		</mnav-bar>

		<!-- 顶部背景图 -->
		<view class="hesderImg">
			<image class="img" :src="activity.images[0] ? (https + activity.images[0].host + activity.images[0].original) : 'http://www.royole.com/image/catalog/banner/2020/home_banner_wing3_cn_2020032601.jpg'"
			 mode="aspectFill" />
		</view>

		<view class="header">
			<view class="content">
				<view class="title text-cut-2">{{activity.name}}</view>
			</view>
		</view>
		<view class="section">
			<view class="list">
				<view class="left">
					<image class="time" src="../static/a01.png" />
				</view>
				<view>{{ activity.target_user_tag?activity.target_user_tag:'全员参与' }} </view>
			</view>
			<view class="list" v-if="activity.start_time">
				<view class="left">
					<image class="time" src="../static/a02.png" />
				</view>
				<view>{{difftimeStr}}</view>
			</view>
			<view class="list" v-if="activity.address">
				<view class="left">
					<image class="local" src="../static/a03.png" mode="widthFix" />
				</view>
				<view class="localText">{{activity.address}}</view>
			</view>
		</view>
		<view class="activeDetail">
			<view>
				<view class="title">活动详情</view>
				<view class="content">{{ activity.detail?activity.detail:''}}</view>
			</view>
			<view>
				<view class="title">注意事项</view>
				<view class="content">
					{{activity.prompt?activity.prompt:''}}
				</view>
			</view>
		</view>
		<view style="background-color: #ffffff; padding-bottom: 40upx;" v-if="activity.location">
			<view class="mapContainer" @tap="goHere(longitude, latitude)">
				<map id="map" class="map" :longitude="longitude" :latitude="latitude" scale="14" :covers="covers" :controls="controls"
				 bindcontroltap="controltap" :markers="markers" bindmarkertap="markertap" :polygons="polygons" :polyline="polyline"
				 :circles="circles" @bindregionchange="regionchange" show-location></map>
				<view class="modeClick" @tap="goHere(longitude, latitude)"></view>
			</view>
		</view>
		<!-- 只有 进行中 的活动才有下面的逻辑（报名或者没有报名的状态不一致） -->
		<view class="btn-box" v-if="activity.type_status === '进行中' ">
			<view class="container">
				<view class="left" :data-id="activity.id" @click="goShowImage">
					<view class="img">
						<image src="../static/msg.png"></image>
					</view>
					<view class="commentNum"> {{ feed_count }} </view>
				</view>
				<!-- 如果当前用户未报名则  -->
				<view class="right">
					<view class="lookList" @click="userList">查看名单</view>
					<view class="btn active" v-if="wantJoin">已参与</view>
					<!-- <view class="btn" v-if="wantJoin" :data-id="activity.id" @click="goPublish">活动晒图</view> -->
					<view class="btn" v-if="!wantJoin && activity.sigin_status !== '报名人数已满' " @click="toJoin">立即参与</view>
					<view class="btn active" v-if="!wantJoin && activity.sigin_status === '报名人数已满' ">名额已满</view>
				</view>
			</view>
		</view>

		<!-- 只有 进行中 的活动才有下面的逻辑（报名或者没有报名的状态不一致） -->
		<view class="btn-box" v-if="activity.type_status === '已结束' ">
			<view class="container">
				<view class="left" :data-id="activity.id" @click="goShowImage">
					<view class="img">
						<image src="../static/msg.png"></image>
					</view>
					<view class="commentNum"> {{ feed_count }} </view>
				</view>
				<!-- 如果当前用户未报名则  -->
				<view class="right">
					<view class="lookList" @click="userList">查看名单</view>
					<!-- <view class="btn" v-if="wantJoin" :data-id="activity.id" @click="goPublish">活动晒图</view> -->
					<!-- <view class="btn active" v-if="wantJoin">已参与</view> -->
					<view class="btn active">已结束</view>
				</view>
			</view>
		</view>


		<!-- 调用登陆插件 -->
		<login></login>
	</view>
</template>

<script>
	import {
		$storage
	} from '@/utils'
	export default {
		data() {
			return {
				https: 'https://',
				id: 0,
				difftimeStr: '',
				feed_count: 0,
				activity: {},
				wantJoin: false,
				comment: [],
				isLoading: false,
				access: '',
				isCreater: false,
				mineId: 0,
				events: {},
				feedCount: '',
				latitude: 0,
				longitude: 0,
				markers: [],
				feed_count: 0,
				user: {},
			}
		},
		components: {
			// login
		},
		created: function() {
			wx.showShareMenu({
			  withShareTicket: true,
			  menus: ['shareAppMessage', 'shareTimeline']
			})
		},
		mounted: function() {},
		onShow: async function() {
			// 数据埋点
			this.$$Rangers.event('page_view', {
			    platform: '小程序',
			})
			console.log('created')
			wx.showLoading({
				title: '加载中',
			})
			let res = await this.$u.api.getActivityDetail(this.id, {});
			
			this.activity = res.data;
			this.$$Rangers.event('campaign_page_view', {
				campaign_name:this.activity.name,
			    platform: '小程序',
			})

			const userTest = $storage.get('user')
			const activeId = this.activity.id
			wx.request({
				url: 'https://mms-api.royole.fun/api/v1/template_type/' + activeId + '?userid=' + userTest.rouyu_uid,
				data: {},
				method: 'GET',
				header: {
					'X-Auth-Token': `${$storage.get('passportToken')}`,
					'Paasport-Device-Id': $storage.get('rouyu-device-id'),
					'Paasport-App-Id': $storage.get('rouyu-app-id'),
					'X-Auth-UID': $storage.get('rouyu-user-id'),
				},
				success: (res) => {
					// 获取当前用户是否报名状态
					this.wantJoin = res.data.data.user_attend;
				},
				fail: (e) => {
					console.log(e)
					return reject(e)
				},
			})


			// debugger
			// this.$set('activity', res.data)
			if (this.activity.location) {
				this.longitude = this.activity.location.lng;
				this.latitude = this.activity.location.lat;
				this.markers = [{
					latitude: this.activity.location.lat,
					longitude: this.activity.location.lng,
					callout: {
						content: this.activity.location.address,
						bgColor: '#fff',
						padding: '5',
						display: 'ALWAYS',
						textAlign: 'center',
						anchorY: '-20',
					}
				}]
				// debugger

			}
			this.difftimeStr = this.diffTime(this.activity.start_time, this.activity.end_time)
			this.user = await this.$u.api.getCurrentUser() || {}
			// debugger
			// const user = $storage.get(`logged`) || {}
			// this.setData({
			//   user,
			// })
			// this.getUserId()
			// this.getBoot()
			wx.hideLoading()
		},
		onLoad: async function(query) {
			// let that = this
			let id = query.id
			// debugger
			if (!id && query.scene) {
				const scene = this.parseQueryString(query.scene)
				id = scene.id
			}
			this.id = id;
			await this.$u.api.getActivityNum(id).then((res) => {
				this.feed_count = res.feed_count
			})
			let _this = this;
			uni.$on("addOneFeed", function() {
				_this.feed_count = parseInt(_this.feed_count) + 1
			});
		},
		methods: {
			// 实现地图导航功能
			goHere(x,y) {
				uni.openLocation({
					latitude: this.activity.location.lat, //要去的纬度-地址       
					longitude: this.activity.location.lng, //要去的经度-地址
					name: this.activity.address, //地址名称
					address: this.activity.location.address, //详细地址名称
					success: function() {
						console.log('导航成功');
					},
					fail: function(error) {
						console.log(error)
					}
				});

			},
			async goPublish(e) {
				const id = e.currentTarget.dataset.id
				let isLogin = await this.$u.api.checkLogin();
				if (!isLogin) {
					return
				}
				uni.navigateTo({
					url: `/pages/share?type=照片&id=${id}`
				})
			},
			goShowImage(e) {
				const id = e.currentTarget.dataset.id
				wx.navigateTo({
					url: `/activities/showImage?id=${id}`,
				})
			},
			userList() {
				const id = this.activity.id
				// 数据埋点
				this.$$Rangers.event('check_name_list', {
					activity_name: this.activity.name,
				    platform: '小程序',
				})
				wx.navigateTo({
					url: `/activities/userList?id=${id}`,
				})
			},
			goBack() {
				uni.navigateBack({
					delta: 1,
				})
			},
			/**想加入 */
			async toJoin() {
				if (this.activity.is_login) {
					const userTest = $storage.get('user')
					if (userTest !== undefined) {
						const activeId = this.activity.id
						if (userTest.rouyu_uid) {
							new Promise((resolve, reject) => {
								wx.request({
									url: 'https://mms-api.royole.fun/api/v1/template_type/' + activeId + '?userid=' + userTest.rouyu_uid,
									data: {},
									method: 'GET',
									header: {
										'X-Auth-Token': `${$storage.get('passportToken')}`,
										'Paasport-Device-Id': $storage.get('rouyu-device-id'),
										'Paasport-App-Id': $storage.get('rouyu-app-id'),
										'X-Auth-UID': $storage.get('rouyu-user-id'),
									},
									success: (res) => {
										return resolve(res.data)
										// }
									},
									fail: (e) => {
										console.log(e)
										return reject(e)
									},
								})
							}).then((res) => {
								console.log('res+++', res)
								if (res.data.user_attend) {
									return wx.showToast({
										title: '您已报名',
										icon: 'none',
										duration: 1000,
									})
								} else {
									if (res.data.template_id) {
										console.log('有template_id，跳webview')
										// https://mms-client.vercel.app/activity/:id?token=xxx
										// const activityId = this.activity.id
										wx.navigateTo({
											url: '/activities/joinActivity?activityId=' + activeId,
										})
									} else {
										console.log('没有template_id，直接去报名')
										new Promise((resolve, reject) => {
											wx.request({
												url: `https://mms-api.royole.fun/api/v1/record/business/${this.activity.template_id}`,
												method: 'POST',
												header: {
													'X-Auth-Token': `${$storage.get('passportToken')}`,
													'Paasport-Device-Id': $storage.get('rouyu-device-id'),
													'Paasport-App-Id': $storage.get('rouyu-app-id'),
													'X-Auth-UID': $storage.get('rouyu-user-id'),
												},
												success: (res) => {
													console.log(res.statusCode === 401)
													if (res.statusCode === 401) {
														uni.$emit('login')
														return reject(false)
													} else if (res.statusCode !== 200) {
														return reject('报名失败')
													}
													return resolve(true)
												},
												fail: (e) => {
													wx.showToast({
														title: '报名失败',
														icon: 'none',
														duration: 1000,
													})
													return reject('报名失败')
												},
											})
										}).then((res) => {
											if (res) {
												// 数据埋点
												this.$$Rangers.event('enroll', {
													activity_name: this.activity.name,
												    platform: '小程序',
												})
												// $event.emit('activityChange', this.data.activity)
												wx.showToast({
													title: '报名成功',
													duration: 1000,
												})
												this.wantJoin = true
											} else {
												wx.showToast({
													title: '报名失败',
													icon: 'none',
													duration: 1000,
												})
											}
										}).catch((res) => {
											wx.showToast({
												title: '报名失败',
												icon: 'none',
												duration: 1000,
											})
										})
									}
								}
							})
						}
					} else {
						uni.$emit('login')
					}
				} else {
					if (this.activity.template_id) {
						console.log('有template_id，跳webview')
						const activityId = this.activity.id
						wx.navigateTo({
							url: '/activities/joinActivity?activityId=' + activityId,
						})
					} else {
						console.log('没有template_id，直接去报名')
						// rouyuActivityApi.joinActivity(this.data.activity.template_id)
						new Promise((resolve, reject) => {
							wx.request({
								url: `https://mms-api.royole.fun/api/v1/record/business/${this.activity.template_id}`,
								method: 'POST',
								header: {
									'X-Auth-Token': `${$storage.get('passportToken')}`,
									'Paasport-Device-Id': $storage.get('rouyu-device-id'),
									'Paasport-App-Id': $storage.get('rouyu-app-id'),
									'X-Auth-UID': $storage.get('rouyu-user-id'),
								},
								success: (res) => {
									console.log(res.statusCode === 401)
									if (res.statusCode === 401) {
										uni.$emit('login')
										return reject('请先登录')
									} else if (res.statusCode !== 200) {
										return reject('报名失败')
									}
									return resolve(true)
								},
								fail: (e) => {
									return reject('报名失败')
								},
							})
						}).then((res) => {
							if (res) {
								// $event.emit('activityChange', this.data.activity)
								// 数据埋点
								this.$$Rangers.event('enroll', {
									activity_name: this.activity.name,
								    platform: '小程序',
								})
								wx.showToast({
									title: '报名成功',
									duration: 1000,
								})
								this.wantJoin = true
							} else {
								wx.showToast({
									title: '报名失败',
									icon: 'none',
									duration: 1000,
								})
							}
						})
					}
				}
			},
			diffTime(startTime, endTime) {
				// console.log('时间：', startTime, endTime)
				const start = this.formatTimestamp(startTime)
				const end = this.formatTimestamp(endTime)

				// const start = '2020-10-2 19:20'
				// const end = '2020-10-2 20:30'
				const time = this.timeAgo(start, end)
				// console.log('time++++', time)

				return time
			},
			timeAgo(faultDate, completeTime) {
				// console.log('0000000000000000000000', faultDate, completeTime)
				var startT = faultDate.replace(/-/g, '/')
				var enfT = completeTime.replace(/-/g, '/')

				// @ts-ignore

				var stime = Date.parse(this.getDate(startT))
				// @ts-ignore
				var etime = Date.parse(this.getDate(enfT))

				// @ts-ignore
				// var stime = Date.parse(getDate(faultDate))
				// var etime = Date.parse(getDate(completeTime))

				// var etime = completeTime.createTime.replace(/-/g, '/')

				var usedTime = etime - stime //两个时间戳相差的毫秒数
				var days = Math.floor(usedTime / (24 * 3600 * 1000))
				//计算出小时数
				var leave1 = usedTime % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
				var hours = Math.floor(leave1 / (3600 * 1000))
				//计算相差分钟数
				var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
				var minutes = Math.floor(leave2 / (60 * 1000))
				var dayStr = days == 0 ? '' : days + '天'
				var hoursStr = hours == 0 ? '' : hours + '小时'
				var time = '时长' + dayStr + hoursStr + minutes + '分钟'
				// @ts-ignore
				var timestamp = Date.parse(this.getDate())
				var date = this.getDate(timestamp)
				//获取年份
				var Y = date.getFullYear()
				var YY = faultDate.substring(0, 4)
				if (Y != YY) {
					return faultDate + ' ~ ' + completeTime
				} else {
					if (days > 1) {
						var start = faultDate.slice(5)
						var end = completeTime.slice(5)
						return start + ' ~ ' + end
					} else {
						return time
					}
				}
			},
			getDate(d) {
				return d ? new Date(d) : new Date()
			},
			/** 将时间戳转换 */
			formatTimestamp(d, format = 'YYYY-MM-DD hh:mm') {
				const date = this.getDate(d)
				let hour = date.getHours()
				let minute = date.getMinutes()
				let second = date.getSeconds()
				const year = date.getFullYear()
				let month = date.getMonth()
				let day = date.getDate()
				if (hour < 10) {
					hour = '0' + hour
				}
				if (minute < 10) {
					minute = '0' + minute
				}
				if (second < 10) {
					second = '0' + second
				}
				month = month + 1
				if (month < 10) {
					month = 0 + month
				}
				if (day < 10) {
					day = 0 + day
				}
				const time =
					format === 'YYYY-MM-DD hh:mm' ?
					`${year}-${month}-${day} ${hour}:${minute}` :
					format === 'YYYYMMDDhhmmss' ?
					`${year}${month}${day}${hour}${minute}${second}` :
					`${year}-${month}-${day} ${hour}:${minute}:${second}`

				return time
			},
			/** 将 query string 转化为对象 */
			parseQueryString(str) {
				return JSON.parse(
					'{"' +
					decodeURIComponent(str).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') +
					'"}',
				)
			}
		},
	}
</script>

<style lang="scss">
	@import '../var.scss';

	page {
		background-color: $page-background-color;
	}

	.hicon {
		height: 32upx;
		width: 32upx;
		padding-left: 30upx;
		padding-top: 10upx;
	}

	.noBorder {
		border-bottom-color: #fff !important;
	}

	.header {
		display: flex;
		width: 100%;
		padding: 40upx 30upx 20upx;
		background-color: #fff;

		.content {
			flex: 1;

			.title {
				color: #001432;
				font-size: 36upx;
				line-height: 50upx;
			}

			.detail {
				display: flex;
				flex: 1;
				align-items: center;
				justify-content: space-between;
				height: 40upx;
				margin-top: 20upx;

				.price {
					color: $price-color;
					font-weight: 600;
					font-size: 40upx;

					text {
						font-size: 24upx;
					}
				}

				.right {
					color: $info-color;
					font-size: 24upx;
				}
			}
		}
	}

	.section {
		width: 100%;
		padding: 15upx 30upx;
		background-color: #fff;

		.list {
			display: flex;
			align-items: center;
			width: 100%;
			padding: 30upx 0;
			color: #465564;
			font-size: 30upx;

			.left {
				display: flex;
				align-items: center;
			}

			image {
				margin-right: 30upx;
			}

			text {
				color: #465564;
				font-weight: 600;
				font-size: 28upx;
			}

			.user {
				width: 27upx;
				height: 31upx;
			}

			.time {
				width: 28upx;
				height: 28upx;
			}

			.local {
				width: 26upx;
				height: 35upx;
			}

			.actdetail {
				width: 29upx;
				height: 29upx;
			}

			&:last-child {
				border: none;
			}
		}

		.quill-image {
			width: 100%;
			height: auto;
		}

		.richText {
			color: $text-color !important;
		}
	}

	.activeDetail {
		padding: 0 30upx 30upx;
		background-color: #fff;
		margin-top: 20upx;

		.title {
			color: #001432;
			font-size: 36upx;
			padding-top: 48upx;
			margin-bottom: 20upx;
		}

		.content {
			color: #465564;
			font-size: 28upx;
			padding-bottom: 30upx;
			line-height: 48upx;
		}
	}

	.mapContainer {
		width: 90%;
		margin: 0 auto 200upx auto;
		position: relative;

		.map {
			width: 100%;
			height: 400upx;
		}

		.modeClick {
			width: 100%;
			height: 400upx;
			background-color: rgba(255, 255, 255, 0);
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
		}
	}

	.comment {
		width: 100%;
		margin-top: 20upx;
		padding: 34upx 0upx 100upx;
		background-color: #ffffff;

		.title {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 30upx;
			font-size: 30upx;

			// background-color: yellow;
			.publish {
				display: flex;
				align-items: center;

				image {
					width: 26upx;
					height: 28upx;
					margin-right: 10upx;
				}
			}
		}
	}

	.noComment {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 50px 0 150upx;
	}

	.operation {
		position: fixed;
		right: 60upx;
		bottom: 60upx;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100upx;
		height: 100upx;
		color: #fff;
		background-color: $primary-color;
		border-radius: 50%;
	}

	.hesderImg {
		width: 100%;
		height: 376upx;

		.img {
			width: 100%;
			height: 100%;
		}
	}

	.btn-box {
		height: 150upx;
		width: 750upx;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 9999;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		margin-top: 45upx;
		padding: 0 32upx;
		background-color: #ffffff;

		.container {
			width: 100%;
			height: 100%;
			position: relative;
		}

		.left {
			position: absolute;
			left: 20upx;
			top: 50upx;
			width: 80upx;
			height: 50upx;
			display: flex;
			flex-direction: row;
			align-items: center;
			// background-color: #0046f5;
			position: relative;

			.img {
				width: 32upx;
				height: 32upx;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.commentNum {
				position: absolute;
				top: 0;
				left: 40upx;
				color: #8c96a5;
				font-size: 20upx;
			}
		}

		.right {
			position: absolute;
			right: 20upx;
			top: 50upx;
			display: flex;
			flex-direction: row;
			align-items: center;

			.lookList {
				width: 220upx;
				height: 64upx;
				line-height: 64upx;
				border-radius: 32upx;
				text-align: center;
				background-color: #ffffff;
				border: 1px solid rgba(218, 221, 225, 1);
				margin-right: 12upx;
			}

			.btn {
				width: 220upx;
				height: 64upx;
				color: #fff;
				font-size: 30upx;
				line-height: 64upx;
				text-align: center;
				background-color: #0046f5;
				border-radius: 32upx;
				margin-left: 12upx;
			}

			.active {
				background: rgba(204, 204, 204, 1);
			}
		}
	}
</style>
